import pyodbc as db
import BaseFunction as BF
import 笔趣阁 as bqg
import 搜搜小说网 as ss
import 第二课堂 as xbqg
import MyClass as mc
import sys
import time
import pymssql as ms


def SaveBookInfo(b):
    BF.save2mysql("Insert into BooksInfo Values(%s,%s,%s,%s,%s,%s,%s)",
                  [(b.name, b.type1, b.author, b.source, b.href, b.utime, 1)], **BF.sqlparms)
    b.ID = BF.selectmssql("Select BID From BooksInfo Where Name=%s and Author=%s",
                          (b.name, b.author), **BF.sqlparms)[0]['BID']


def GetBody(zjc, mode):
    if mode == 0:
        zjc = bqg.GetBody(zjc)
    if mode == 1:
        zjc = ss.GetBody(zjc)
    if mode == 2:
        zjc = xbqg.GetBody(zjc)
    return zjc


# 最终保存
def LastSave(zjc, BcList, fromWhere, b, b1, b2):
    if fromWhere == 0:
        SaveBookInfo(b)
        zjc = GetBody(zjc, 0)
        try:
            BF.Save(zjc, b.ID)
            BF.ExcuteOneSQLAndOnePrams("insert into UpdateInfo(BID,State,Num,IsDispose) values(%s,%s,%s,%s)",
                                       (b.ID, 0, len(zjc), 0))
        except Exception as err:
            BF.save2mysql("Delete From BooksInfo Where Name=%s and Author=%s",
                          [(b.name, b.author)], **BF.sqlparms)
            print(err)

    elif fromWhere == 1:
        if len(b2) > 0:
            BcList[2].remove(b2[0])
        # 保存书信息
        SaveBookInfo(b1[0])
        # 移除源2中的这本书
        BcList[1].remove(b1[0])
        # 保存章节
        zjc = GetBody(zjc, 1)
        try:
            BF.Save(zjc, b1[0].ID)
            BF.ExcuteOneSQLAndOnePrams("insert into UpdateInfo(BID,State,Num,IsDispose) values(%s,%s,%s,%s)",
                                       (b1[0].ID, 0, len(zjc), 0))
        except Exception as err:
            BF.save2mysql("Delete From BooksInfo Where Name=%s and Author=%s", \
                          [(b1[0].name, b1[0].author)], **BF.sqlparms)
            print(err)

    elif fromWhere == 2:
        if len(b1) > 0:
            BcList[1].remove(b1[0])
        SaveBookInfo(b2[0])
        BcList[2].remove(b2[0])
        zjc = GetBody(zjc, 2)
        try:
            BF.Save(zjc, b2[0].ID)
            BF.ExcuteOneSQLAndOnePrams("insert into UpdateInfo(BID,State,Num,IsDispose) values(%s,%s,%s,%s)",
                                       (b2[0].ID, 0, len(zjc), 0))
        except Exception as err:
            BF.save2mysql("Delete From BooksInfo Where Name=%s and Author=%s", \
                          [(b2[0].name, b2[0].author)], **BF.sqlparms)
            print(err)
    print('保存成功！')


def Search(bkName):
    BcList = []
    # 添加所有源网站搜索结果
    BF.AppendBook(BcList, bkName)
    print('关键词：' + str(bkName))
    # 没有结果
    if len(BcList[0]) == 0:
        print('无结果')
        return
    for i in range(0, len(BcList)):
        for b in BcList[i]:
            if BF.selectmssql('Select COUNT(BID) C From BooksInfo Where Name=%s and Author=%s', (b.name, b.author),
                              **BF.sqlparms)[0]['C'] > 0:
                continue
            # 是否为第一个源网站的资源
            if i == 0:
                fromWhere = i
                # 获取第一个搜索源的章节列表
                zjc = bqg.ZJIndex(b.href)
                # 获取另外网站是否有重复的小说
                b1 = list(filter(lambda x: x.name == b.name and x.author == b.author, BcList[1]))
                b2 = list(filter(lambda x: x.name == b.name and x.author == b.author, BcList[2]))
                try:  # 有重复的 判断章节数量 储存章节数量多的
                    b1zjc = ss.GetChapterList(b1[0].href)
                    if len(b1zjc) > len(zjc):
                        zjc = b1zjc
                        fromWhere = 1
                except Exception as error:
                    print("仅源1中存在该小说")

                try:
                    b2zjc = xbqg.GetChapterList(b2[0].href)
                    if len(b2zjc) > len(zjc):
                        zjc = b2zjc
                        fromWhere = 2
                except Exception as error:
                    print("仅源1中存在该小说")

                LastSave(zjc, BcList, fromWhere, b, b1, b2)

            # 是否为第二个源网站的资源  与第三个网站查重 
            elif i == 1:
                fromWhere = i

                zjc = ss.GetChapterList(b.href)
                b2 = list(filter(lambda x: x.name == b.name and x.author == b.author, BcList[2]))
                try:
                    b2zjc = xbqg.GetChapterList(b2[0].href)
                    if len(b2zjc) > len(zjc):
                        zjc = b2zjc
                        fromWhere = 2
                except Exception as err:
                    print(err)
                if len(b2) > 0:
                    BcList[2].remove(b2[0])
                    # 保存书信息
                    SaveBookInfo(b1[0])
                    # 移除源2中的这本书
                    BcList[1].remove(b1[0])
                    # 保存章节
                    zjc = GetBody(zjc, 1)
                    try:
                        BF.Save(zjc, b1[0].ID)
                    except Exception as err:
                        BF.save2mysql("Delete From BooksInfo Where Name=%s and Author=%s", \
                                      [(b1[0].name, b1[0].author)], **BF.sqlparms)
                        print(err)

            elif i == 2:
                fromWhere = i
                zjc = xbqg.GetChapterList(b.href)
                zjc = xbqg.GetBody(zjc)
                SaveBookInfo(b)
                try:
                    BF.Save(zjc, b.ID)
                except Exception as err:
                    BF.save2mysql("Delete From BooksInfo Where Name=%s and Author=%s", \
                                  [(b.name, b.author)], **BF.sqlparms)
                    print(err)


def Start():
    rows = BF.selectmssql('select search,ID from SearchRecord where State>0', (), **BF.sqlparms)
    for row in rows:
        Search(row['search'])
        BF.myssqlUpdate('Update SearchRecord Set State = 0 where ID=' + str(row['ID']), [], **BF.sqlparms)
    else:
        print("没有需要爬取的")


Start()
input('按任意键结束')
